import Vue from 'vue'
import Router from 'vue-router'
import Framework from "../components/framework/Framework";
import Login from "../components/login/Login.vue"
import Home from "../components/content/home/Home.vue"
import HouseList from "../components/content/house/houseList/HouseList.vue"
import PersonMessage from "../components/content/personMessage/PersonMessage.vue"
import Error from "../components/error/Error.vue"
import {tokenCheck} from "../assets/js/tokenCheck"
import UserList from "../components/content/user/userList/UserList.vue";
import {Message} from "element-ui";
import RentalApply from "../components/content/apply/rentalApplication/RentalApply.vue";
import LeaseTerminationApply from "../components/content/apply/leaseTerminationApplication/LeaseTerminationApply.vue";
import HouseStatistics from "../components/content/house/houseStatistics/HouseStatistics.vue";
import AccountList from "../components/content/managerUser/accountList/AccountList.vue";
import NoticeList from "../components/content/notice/noticeList/NoticeList.vue";
import InsertNotice from "../components/content/notice/insertNotice/InsertNotice.vue";
import InspectionDispatch from "../components/content/patrolOversight/inspectionDispatch/InspectionDispatch.vue";
import ProblemReporting from "../components/content/patrolOversight/problemReporting/ProblemReporting.vue";
import OpinionExam from "../components/content/feedbackOponion/opinion/OpinionExam.vue";
import AuthorityManagement from "../components/content/managerUser/authorityManagement/AuthorityManagement.vue";
import UserType from "../components/content/user/userType/UserType.vue";
import OpinionList from "../components/content/feedbackOponion/feedbackList/OpinionList.vue";

Vue.use(Router);

//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location)
  //  .catch(err => err)
}

const routes = [
  {
    path: '/', // 默认路由
    redirect: '/login', // 将默认路由重定向到登录页面
  },
  {
    path: '/login',
    name: Login,
    component: Login
  },
  {
    path: '/framework',
    name: Framework,
    component: Framework,
    meta: { requiresAuth: true },    // 这个元数据表示需要登录验证才能进入路由，同时可以限制其子路由
    children: [
      {
        path: 'error',
        name: Error,
        component: Error
      },
      {
        path: 'personMessage',
        name: PersonMessage,
        component: PersonMessage
      },
      {
        path: 'home',
        name: Home,
        component: Home
      },
      {
        path: 'houseList',
        name: HouseList,
        component: HouseList
      },
      {
        path: 'houseStatistics',
        name: HouseStatistics,
        component: HouseStatistics
      },
      {
        path: 'userList',
        name: UserList,
        component: UserList
      },
      {
        path: 'userType',
        name: UserType,
        component: UserType
      },
      {
        path: 'rentalApply',
        name: RentalApply,
        component: RentalApply
      },
      {
        path: 'leaseTerminationApply',
        name: LeaseTerminationApply,
        component: LeaseTerminationApply
      },
      {
        path: 'noticeList',
        name: NoticeList,
        component: NoticeList
      },
      {
        path: 'insertNotice',
        name: InsertNotice,
        component: InsertNotice
      },
      {
        path: 'inspectionDispatch',
        name: InspectionDispatch,
        component: InspectionDispatch,
      },
      {
        path: 'problemReporting',
        name: ProblemReporting,
        component: ProblemReporting
      },
      {
        path: 'opinionExam',
        name: OpinionExam,
        component: OpinionExam
      },
      {
        path: 'opinionList',
        name: OpinionList,
        component: OpinionList
      },
      {
        path: 'accountList',
        name: AccountList,
        component: AccountList
      },
      {
        path: 'authorityManagement',
        name: AuthorityManagement,
        component: AuthorityManagement
      },
    ]
  }
];

const router = new Router({
  mode: 'history',
  routes
});

// 导航守卫
router.beforeEach(async (to,from,next) => {
  // 如果目标路由需要登录权限
  if(to.matched.some(record => record.meta.requiresAuth)){
    if(from.fullPath === "/login"){
      sessionStorage.setItem('pathFrom',from.fullPath);
      next();
    } else {
      try {
        const loggedIn = await isLoggedIn();
        if (!loggedIn) {
          // 如果未登录，则重定向到登录页面
          next({
            path: '/login'
            // query : {redirect: to.fullPath} // 保存用户尝试访问的页面，这个会在login后面加上访问的路径
          });
        } else {
          // 如果已登录，则继续导航
          next();
        }
      } catch (error) {
        console.error("登录状态检查失败:", error);
        next('/error'); // 导航到错误页面
      }
    }
  } else {
    // 如果目标路由不需要登录权限，则直接导航
    next();
  }
});

async function isLoggedIn() {
  // 根据实际情况检查用户是否已登录
  // 返回true表示已登录，false则表示未登录

  /* 登录检验 */
  /*
    !!!!!!!!!!!!!
    这里有一个问题，由于tokenCheck是一个异步函数，导航守卫中没有等待这个执行完就返回了一个undefine
    所以会导致逻辑出现问题，解决这个问题需要将导航守卫也变成异步，因为is这个函数中不可使用await，而在导航守卫中可以使用async来变为异步
   */

  try {
    const res = await tokenCheck();
    if (res.code === '200') {
      // 请求成功
      return true;
    } else if (res === 401) {
      Message({
        message: "登录过期，请重新登录！",
        type: 'error',
        duration: 3 * 1000
      });
    }
    // 其他返回码
    return false;
  } catch (error) {
    // 大概率是后台系统没有启动导致请求没有发送出去，所以直接false
    console.log("出错了：" + error);
    return false;
  }
}
export default router;
